package cn.wsh.org.service.impl;

import cn.wsh.basic.service.impl.BaseServiceImpl;
import cn.wsh.org.domain.Detail;
import cn.wsh.org.domain.Detail;
import cn.wsh.org.mapper.DetailMapper;
import cn.wsh.org.service.IDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName : DetailImpl
 * Author : "吴----"
 * @date : 2022/2/9 22:40
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DetailServiceImpl extends BaseServiceImpl<Detail> implements IDetailService {
    @Autowired
    private DetailMapper detailMapper;

    @Override
    public void batch(List<Long> ids) {
        detailMapper.batch(ids);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
        detailMapper.delete2();
    }


    public List<Detail> queryTree() {
//        *    1.一次性查询出所有数据，放到内存 all
        List<Detail> allDepts = detailMapper.loadAll();
        //为了下面内层嵌套循环，查询父亲方便，我们这里把所有数据，抽成map<部门ID，部门对象>
        /*Map<Long, Detail> allDeptMap =
                allDepts.stream().collect(Collectors.toMap(Detail::getId, dept -> dept));*/
        HashMap<Long, Detail> allDeptMap = new HashMap<>();
        for (Detail tmp : allDepts) {
            allDeptMap.put(tmp.getId(), tmp);
        }

        List<Detail> firstDepts = new ArrayList<>();
        for (Detail deptTmp : allDepts) {
            if (deptTmp.getTypes_id() == null) {//代表是顶级
//        *    2.从所有数据中找出第一层级 firstDetail   我们需要返回的数据
                firstDepts.add(deptTmp);
            } else {
                // 可能是第二、第三、第四......
//        *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Detail parent = allDeptMap.get(deptTmp.getTypes_id());
                if (parent != null) {
                    parent.getChildren().add(deptTmp);
                }

                /*for(Detail parent : allDepts){
                    if(deptTmp.getParent().getId() == parent.getId()){
                        //把我加到你的儿子里面
                        parent.getChildren().add(deptTmp);
                    }
                    continue;
                }*/
            }
        }
        return firstDepts;


    }

}
